package com.chenailin.www.controller.auth;

import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @author evi
 */
@WebServlet("/captcha")
public class CaptchaController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        // 1. 生成验证码（示例使用简单实现）
        String captchaText = generateRandomCode(4);
        String token = UUID.randomUUID().toString();

        // 2. 存储到Session（用于后续验证）
        req.getSession().setAttribute("captchaToken", token);
        System.out.println(token);
        req.getSession().setAttribute("captchaText", captchaText);
        System.out.println(captchaText);
        // 3. 返回JSON响应
        resp.setContentType("application/json");
        Map<String, String> responseData = new HashMap<>();
        // 示例
        responseData.put("image", generateDummyImageUrl(captchaText));
        responseData.put("token", token);

        resp.getWriter().write(new Gson().toJson(responseData));
    }

    private String generateRandomCode(int length) {
        // 简单随机字母数字生成
        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    private String generateDummyImageUrl(String code) {
        // 临时方案：使用第三方验证码图片生成服务
        return "https://dummyimage.com/100x40/000/fff&text=" + code;
    }
}